{% extends 'base.html' %}
{% load staticfiles %}

{% block head %}
    <link rel="stylesheet" href="{% static 'AdminLTE/bower_components/select2/dist/css/select2.min.css' %}">
    <link rel="stylesheet" href="{% static 'jquery-confirm/dist/jquery-confirm.min.css' %}">
    <link rel="stylesheet" href="{% static 'modaal/css/modaal.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/selectize.css' %}">
    <style>
        .col-sm-10 {
            width: 40%;
        }

        .has-select-error {
            border: 1px solid red;
        }

        p.lead {
            border-bottom: 1px solid #33333361;
            padding-bottom: 5px;
        }
    </style>
{% endblock %}

{% block content %}
    <div id="ip_select_form" style="display:none;">
        <div class="col-xs-12">
            <div class="box no-border no-shadow">
                <div class="box-header">
                    <h3 class="box-title">请选择IP地址</h3>
                </div>
                <div class="box-body">
                    <form class="form-horizontal" style="margin-top: 20px;" id="ip_detail_form">
                        <div class="form-group">
                            <label for="IP_segment" class="col-sm-2 control-label">IP网段</label>
                            <div class="col-sm-9">
                                <select name="IP_segment" id="IP_segment" style="display: none;">
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="IP_state" class="col-sm-2 control-label">IP状态</label>
                            <div class="col-sm-9">
                                <select style="display: none;" name="IP_state" id="IP_state">
                                    <option value="0">空闲</option>
                                    <option value="1">占用</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="IP" class="col-sm-2 control-label">IP地址</label>
                            <div class="col-sm-9">
                                <select name="IP" id="IP" style="display: none;">
                                </select>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="box-footer no-border">
                    <div class="pull-right">
                        <button type="button" class="btn btn-default" onclick="$('#ip_select').modaal('close');">关闭</button>&nbsp;&nbsp;&nbsp;&nbsp;
                        <button type="button" class="btn btn-info" onclick="confirmIPSelect();">确认</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <form class="form-horizontal" id="asset_form" style="min-width: 500px;">
        <div class="box-body">
            <div class="form-group">
                <label for="asset_type" class="col-sm-2 control-label">资产类型<span class="text-red">*</span></label>
                <div class="col-sm-10">
                    <select class="form-control select2" id="asset_type" name="asset_type" onchange="assetType();$('#hosted_on').val('').trigger('change');$('.hosted_on').hide();" style="width:100%;">
                        <option>请选择资产类型</option>
                        {% for asset_type in asset_types %}
                            <option value="{{ asset_type.0 }}">{{ asset_type.1 }}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label for="device_type" class="col-sm-2 control-label">设备类型<span class="text-red">*</span></label>
                <div class="col-sm-10">
                    <select class="form-control select2" id="device_type" name="device_type" onchange="deviceType()" style="width:100%;"></select>
                </div>
            </div>
            <div class="form-group hosted_on">
                <label for="hosted_on" class="col-sm-2 control-label">宿主机</label>
                <div class="col-sm-10">
                    <select class="form-control" id="hosted_on" name="hosted_on" style="width:100%;">
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label for="asset_nu" class="col-sm-2 control-label">资产编号/资产名称<span class="text-red">*</span></label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="asset_nu" id="asset_nu">
                </div>
            </div>
            <div class="form-group">
                <label for="asset_product" class="col-sm-2 control-label">产品名称</label>
                <div class="col-sm-10">
                    <select style="display: none;" name="asset_product" id="asset_product">
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label for="asset_status" class="col-sm-2 control-label">设备状态<span class="text-red">*</span></label>
                <div class="col-sm-10">
                    <select class="form-control" name="asset_status" id="asset_status">
                        {% for asset_status in asset_status_ %}
                            <option value="{{ asset_status.0 }}">{{ asset_status.1 }}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>
            <input type="text" style="display: none" name="asset_admin" id="asset_admin" value="{{ asset_admin.id }}">
            <div class="form-group">
                <label for="asset_management_ip" class="col-sm-2 control-label">管理IP<span class="text-red">*</span></label>
                <div class="col-sm-10">
                    <div class="input-group">
                        <input name="asset_management_ip" id="asset_management_ip" style="display: none;">
                        <input class="form-control" id="asset_management_ip_value" readonly>
                        <a type="button" class="input-group-addon btn btn-primary" id="ip_select" data-modaal-type="inline" data-modaal-animation="fade" onclick="assetIpSelect();">选择</a>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label for="asset_environment" class="col-sm-2 control-label">设备环境<span class="text-red">*</span></label>
                <div class="col-sm-10">
                    <select class="form-control" name="asset_environment" id="asset_environment">
                        {% for asset_environment in asset_environment_ %}
                            <option value="{{ asset_environment.0 }}" {% if asset_environment.0 == 1  %}selected="selected"{% endif %}>{{ asset_environment.1 }}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label for="asset_memo" class="col-sm-2 control-label">备注</label>
                <div class="col-sm-10">
                    <textarea class="form-control" name="asset_memo" id="asset_memo"></textarea>
                </div>
            </div>
            <div class="form-group">
                <label for="asset_applicant" class="col-sm-2 control-label">申请人</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="asset_applicant" id="asset_applicant">
                </div>
            </div>
            <div class="form-group">
                <label for="asset_runner" class="col-sm-2 control-label">负责人</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="asset_runner" id="asset_runner">
                </div>
            </div>
            <div class="form-group">
                <label for="asset_purchase_day" class="col-sm-2 control-label">申请/购买日期<span
                        class="text-red">*</span></label>
                <div class="col-sm-10">
                    <input type="date" class="form-control" name="asset_purchase_day" id="asset_purchase_day">
                </div>
            </div>
            <div class="form-group">
                <label for="asset_expire_day" class="col-sm-2 control-label">到期/过保日期<span class="text-red">*</span></label>
                <div class="col-sm-10">
                    <input type="date" class="form-control" name="asset_expire_day" id="asset_expire_day">
                </div>
            </div>

            <div class="form-group">
                <label for="asset_provider" class="col-sm-2 control-label">供应商</label>
                <div class="col-sm-10">
                    <select class="form-control" name="asset_provider" id="asset_provider">
                        <option value="">请选择供应商</option>
                        {% for asset_provider in asset_providers %}
                            <option value="{{ asset_provider.id }}">{{ asset_provider.asset_provider_name }}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label for="asset_model" class="col-sm-2 control-label">资产型号</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="asset_model" id="asset_model">
                </div>
            </div>
            <div class="form-group">
                <label for="asset_price" class="col-sm-2 control-label">价格（万元）</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="asset_price" id="asset_price">
                </div>
            </div>
            <div class="form-group">
                <label for="asset_idc" class="col-sm-2 control-label">所在机房</label>
                <div class="col-sm-10">
                    <select class="form-control" name="asset_idc" id="asset_idc" onchange="idc()">
                        <option value="">请选择机房</option>
                        {% for asset_idc in asset_idcs %}
                            <option value="{{ asset_idc.id }}">{{ asset_idc.idc_name }}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label for="asset_cabinet" class="col-sm-2 control-label">所在机柜</label>
                <div class="col-sm-10">
                    <select class="form-control" name="asset_cabinet" id="asset_cabinet"></select>
                </div>
            </div>
        </div>
        <!-- /.box-body -->

        <div class="box-footer">
            <button type="button" class="btn btn-default pull-right" onclick="history.go(-1)">返回</button>
            <button type="button" class="btn btn-info pull-right" onclick="addAsset(another=false)">确认添加，并返回资产列表
            </button>
            <button type="button" class="btn btn-info pull-right" onclick="addAsset(another=true)">确认添加，继续添加另一个资产
            </button>
        </div>
        <!-- /.box-footer -->
    </form>
{% endblock %}

{% block js %}
    <!-- Select2 -->
    <script src="{% static 'AdminLTE/bower_components/select2/dist/js/select2.full.min.js' %}"></script>
    <script src="{% static 'jquery-confirm/dist/jquery-confirm.min.js' %}"></script>
    <script src="{% static 'modaal/js/modaal.min.js' %}"></script>
    <script src="{% static 'js/selectize.min.js' %}"></script>
    <script>
        $(function () {
            $('#asset_product').selectize({
                valueField: 'id',
                labelField: 'text',
                searchField: 'text',
                placeholder: '请输入搜索条件',
                load: function(query, callback) {
                    $.ajax({
                        url: '/project/find_product_name/',
                        data: {
                            product_name: query
                        },
                        dataType: 'json',
                        type: 'GET',
                        error: function() {
                            callback();
                        },
                        success: function(res) {
                            callback(res.results);
                        }
                    });
                }
            });

            $("#ip_select").modaal({
                width: 600,
                height: 360,
                content_source: '#ip_select_form',
                before_open: function() {
                    $("#ip_detail_form .selectize-input").removeClass('has-select-error').parent().parent().parent().removeClass('has-error').find('span').remove()
                },
            });
            $('.select2').select2();
            $('#hosted_on').select2({
                allowClear: true,
                ajax: {
                    url: '/assets/find_hosted_on',
                    dataType: 'json',
                    data: function (params) {
                        params.offset = 6
                        params.page = params.page || 1
                        var query = {
                            search: params.term,
                            page: params.page,
                            offset: params.offset,
                        }
                        return query;
                    },
                    processResults: function (data, params) {
                        var page = params.page || 1
                        return {
                            results: data.results,
                            pagination: {
                                more: (page*params.offset) < data.total_count
                            }
                        };
                    },
                    cache: true
                  },
                minimumInputLength: 2,
                templateResult: formatRepo,
                templateSelection: formatRepoSelection,
                placeholder: '查询IP地址 或 项目编号/名称'
            });

            function formatRepo (repo) {
                if (repo.loading) {
                    return repo.text;
                }
                var $container = $("<div class='select2-result-repository clearfix'>" +
                      "<div class='select2-result-repository-element'>" + repo.text +
                    "</div></div>");
                return $container;
            }

            function formatRepoSelection (repo) {
                return repo.text;
            }

            $('.hosted_on').hide()
            $('#IP_segment').selectize({
                valueField: 'id',
                labelField: 'text',
                searchField: 'text',
                onChange: function(value){
                    ipDetailSelect()
                }
            });
            $('#IP').selectize({
                valueField: 'id',
                labelField: 'text',
                searchField: 'text',
            });
            $('#IP_state').selectize({
                onChange: function(value){
                    ipDetailSelect()
                }
            })
        });

        function assetIpSelect(){
            var IPSegmentSelect = $('#IP_segment')[0].selectize;
            IPSegmentSelect.clear()
            $.ajax({
                type: 'POST',
                url: '/assets/find_ip_segment/'
            }).then(function (data) {
                IPSegmentSelect.addOption(data.results)
            });
        }

        function ipDetailSelect(){
            var ipSegment = $('#IP_segment').val()
            var ipstate = $('#IP_state').val()
            var IPSelect = $('#IP')[0].selectize
            IPSelect.clear()
            IPSelect.clearOptions()
            if(!ipSegment){
                return
            }
            $.ajax({
                type: 'POST',
                url: '/assets/find_ip/',
                data: {IP_segment: ipSegment, IP_state: ipstate},
            }).then(function (data) {
                IPSelect.addOption(data.results)
            });
        }

        function confirmIPSelect() {
            $(".modaal-container .selectize-input").removeClass('has-select-error').parent().parent().parent().removeClass('has-error').find('span').remove()
            if(!$('#IP_segment').val()){
                mes = '请选择IP网段'
                $('#IP_segment').parent().append('<span class="help-block">'+mes+'</span>').find('.selectize-input').addClass('has-select-error')
                $('#IP_segment').parent().parent().addClass('has-error')
            }
            if(!$('#IP_state').val()){
                mes = '请选择IP状态'
                $('#IP_state').parent().append('<span class="help-block">'+mes+'</span>').find('.selectize-input').addClass('has-select-error')
                $('#IP_state').parent().parent().addClass('has-error')
            }
            var IPSelect = $('#IP')
            var ip = IPSelect.val()
            var text = IPSelect.text()
            if(!ip){
                mes = '请选择IP地址'
                IPSelect.parent().append('<span class="help-block">'+mes+'</span>').find('.selectize-input').addClass('has-select-error')
                IPSelect.parent().parent().addClass('has-error')
                $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '请修改错误信息',
                    })
            } else {
                $('#asset_management_ip').val(ip)
                $('#asset_management_ip_value').val(text)
                $('#ip_select').modaal('close')
            }
        }

        function assetType() {
            let asset_type = $('#asset_type').val();
            let device_obj = $('#device_type');
            let server_text_red = $('[for=asset_management_ip]>.text-red');
            server_text_red.hide();
            if (asset_type === 'server') {
                device_obj.html('<option>请选择设备类型</option>');
                {% for server_type in server_types %}
                    device_obj.append('<option value="' + {{ server_type.0 }} +'">' + '{{ server_type.1 }}' + '</option>');
                {% endfor %}
                server_text_red.show();
            } else {
                $('#asset_product').selectize()[0].selectize.clear(), $('#asset_product').parent().parent().hide(), $('#asset_applicant').val('').parent().parent().hide(), $('#asset_runner').val('').parent().parent().hide(),
                $('#asset_provider').parent().parent().show(), $('#asset_model').parent().parent().show(), $('#asset_price').parent().parent().show(),
                $('#asset_idc').parent().parent().show(), $('#asset_cabinet').parent().parent().show()
                if (asset_type === 'network') {
                    device_obj.html('<option>请选择设备类型</option>');
                    {% for network_type in network_types %}
                        device_obj.append('<option value="' + {{ network_type.0 }} +'">' + '{{ network_type.1 }}' + '</option>');
                    {% endfor %}
                } else if (asset_type === 'office') {
                    device_obj.html('<option>请选择设备类型</option>');
                    {% for office_type in office_types %}
                        device_obj.append('<option value="' + {{ office_type.0 }} +'">' + '{{ office_type.1 }}' + '</option>');
                    {% endfor %}
                } else if (asset_type === 'security') {
                    device_obj.html('<option>请选择设备类型</option>');
                    {% for security_type in security_types %}
                        device_obj.append('<option value="' + {{ security_type.0 }} +'">' + '{{ security_type.1 }}' + '</option>');
                    {% endfor %}
                } else if (asset_type === 'storage') {
                    device_obj.html('<option>请选择设备类型</option>');
                    {% for storage_type in storage_types %}
                        device_obj.append('<option value="' + {{ storage_type.0 }} +'">' + '{{ storage_type.1 }}' + '</option>');
                    {% endfor %}
                } else if (asset_type === 'software') {
                    device_obj.html('<option>请选择设备类型</option>');
                    {% for software_type in software_types %}
                        device_obj.append('<option value="' + {{ software_type.0 }} +'">' + '{{ software_type.1 }}' + '</option>');
                    {% endfor %}
                }
            }
        }

        function deviceType() {
            let asset_type = $('#asset_type').val();
            let device_type = $('#device_type').val();
            let hosted_obj = $('.hosted_on');
            if(asset_type === 'server'){
                $('#asset_product').parent().parent().show(), $('#asset_applicant').parent().parent().show(), $('#asset_runner').parent().parent().show()
                if(device_type === '1'){
                    $('#asset_provider').val('').parent().parent().hide(), $('#asset_model').val('').parent().parent().hide(), $('#asset_price').val('').parent().parent().hide(),
                    $('#asset_idc').val('').parent().parent().hide(), $('#asset_cabinet').val('').parent().parent().hide(), hosted_obj.show()
                } else if(device_type === '2'){
                    $('#asset_provider').parent().parent().show(), $('#asset_model').parent().parent().show(), $('#asset_price').parent().parent().show(),
                    $('#asset_idc').val('').parent().parent().hide(), $('#asset_cabinet').val('').parent().parent().hide()
                    $('#hosted_on').val('').trigger('change'),hosted_obj.hide()
                } else {
                    $('#asset_provider').parent().parent().show(), $('#asset_model').parent().parent().show(), $('#asset_price').parent().parent().show(),
                    $('#asset_idc').parent().parent().show(), $('#asset_cabinet').parent().parent().show()
                    $('#hosted_on').val('').trigger('change'),hosted_obj.hide()
                }
            }
        }

        function idc() {
            let idc_id = $('#asset_idc').val();
            $.ajax({
                url: '/api/idc/' + idc_id + '/',
                type: 'GET',
                success: function (res) {
                    let cabinet_obj = $('#asset_cabinet');
                    let cabinets = res['cabinet'];
                    cabinet_obj.html('');
                    for (let i = 0; i < cabinets.length; i++) {
                        cabinet_obj.append(
                            '<option value=' + cabinets[i]['id'] + '>' + cabinets[i]['cabinet_name'] + '</option>'
                        )
                    }
                }
            })
        }

        // 添加资产
        (function ($) {
            $.fn.formatData = function (assetType) {
                let formatObj = {};
                let assetObj = {};
                let array = this.serializeArray();
                $(array).each(function () {
                    if (this.name.indexOf('asset_') !== -1) {
                        assetObj[this.name] = this.value;
                        formatObj['assets'] = assetObj;
                    } else if (this.name.indexOf('device_') !== -1) {
                        formatObj[assetType + '_type'] = this.value;
                    } else {
                        formatObj[this.name] = this.value;
                    }
                });
                return formatObj;
            };
        })(jQuery);

        function addErrorMessage(errors) {
            $.each(errors, function(name, value){
                $.each(value, function(i, v){
                    $('#'+name).after('<span class="help-block">'+v+'</span>')
                })
                $('#'+name).parent().parent().addClass('has-error')
            })
        }

        function addAsset(another) {
            let assetType = $('#asset_type').val();
            let data = $('.form-horizontal').formatData(assetType);
            $('.help-block').remove()
            $('.form-group').removeClass('has-error')
            $('.has-select-error').removeClass('has-select-error')
            if($('#asset_type').val() == '请选择资产类型'){
                mes = '请选择资产类型'
                $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: mes,
                    })
                $('#asset_type').parent().parent().addClass('has-error')
                $('#asset_type+span').addClass('has-select-error')
                return
            }
            if($('#device_type').val() == '请选择设备类型'){
                mes = '请选择设备类型'
                $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: mes,
                    })
                $('#device_type').parent().parent().addClass('has-error')
                $('#device_type+span').addClass('has-select-error')
                return
            }
            if($('#asset_type').val() == 'server'){
                if(!$('#asset_management_ip').val()){
                    mes = '管理IP不能为空'
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: mes,
                    })
                    $('#asset_management_ip').parent().after('<span class="help-block">'+mes+'</span>')
                    $('[for=asset_management_ip]').parent().addClass('has-error')
                    return
                }
            }

            $.ajax({
                url: '/api/' + assetType + '_assets/',
                type: 'POST',
                data: JSON.stringify(data),
                dataType: 'json',
                contentType: "application/json",
                success: function () {
                    if (another) {
                        $.confirm({
                            title: 'Tips',
                            content: '添加成功！',
                            type: 'green',
                            buttons: {
                                Ok: function () {
                                    document.getElementById("asset_form").reset();
                                    $(".select2").val('').trigger('change');
                                },
                            }
                        })
                    } else {
                        $.confirm({
                            title: 'Tips',
                            content: '添加成功！',
                            type: 'green',
                            buttons: {
                                Ok: function () {
                                    window.location.href = '{% url 'assets_list' %}';
                                },
                            }
                        })
                    }
                },
                error: function (response) {
                    var errors = JSON.parse(response.responseText)
                    if(errors.hasOwnProperty('detail')){
                        $.alert({
                                title: 'Tips',
                                type: 'red',
                                content: errors.detail,
                                buttons: {
                                            Ok: function () {
                                                window.location.href = '/';
                                            },
                                        }
                            });
                        return
                    }
                    if(errors.hasOwnProperty('assets')){
                        var assets_errors = errors.assets
                        if(assets_errors.hasOwnProperty('non_field_errors')){
                            var dateError = assets_errors.non_field_errors[0]
                            $.alert({
                                title: 'Tips',
                                type: 'red',
                                content: dateError,
                            });
                            addErrorMessage({asset_expire_day:[dateError]})
                        } else {
                            addErrorMessage(assets_errors)
                            $.alert({
                                title: 'Tips',
                                type: 'red',
                                content: '请修改错误信息',
                            });
                        }
                    }
                }
            })

        }

    </script>
{% endblock %}